/**
  ******************************************************************************
  * File Name          : ltlx.c
  * Description        : 
  ******************************************************************************
  * @attention
  *
  ******************************************************************************
  */

/* Includes ------------------------------------------------------------------*/
#include "tskcfg.h"
#include "bsp.h"
#include "cf.h"
#include "storage.h"
#include "route_base.h"
#include <string.h>

#define CF_STORAGE_ADDRESS      EEPROM_BLOCK01

Cf_StorageParaType cf_storage_para;
const Cf_ParaType Cf_InitPara = 
{
	.cftmen  = 0,
	.dummy1  = 0,
	.cfot    = 3600,
	
	.cftm[0] = 0,
	.cftm[1] = 0,
	.cftm[2] = 0,
	.cftm[3] = 0,
	.cftm[4] = 0,
	.cftm[5] = 0,
};

Cf_ParaType Cf_RunPara;

volatile Cf_StateType Cf_State = {0};
Cf_StateType Cf_State_last = {1};

uint8_t Cf_ParaCheck(Cf_ParaType *para)
{
  uint8_t i;
  
  if(para->cfot > 59940u)
  {
    return 1;
  }
  
  if((para->cftmen != 0) && (para->cftmen != 1))
  {
    return 2;
  }
  
  for(i=0; i<6; i++)
  {
    if(para->cftm[i] > 86400)
    {
      return 3;
    }
  }
  
  return 0;
}

static void storage_save_initpara(void)
{
  memset(&cf_storage_para, 0, sizeof(Cf_StorageParaType));
  
  cf_storage_para.para = Cf_InitPara;
  
  cf_storage_para.crc16 = crc16((uint8_t *)&cf_storage_para.para, sizeof(Cf_ParaType));
  
  eEPRom_Write(CF_STORAGE_ADDRESS, (const uint8_t*)&cf_storage_para, sizeof(Cf_StorageParaType));
  
  Cf_RunPara = Cf_InitPara;
  
  printf("Cf Init para saved!\r\n");
}

void Storage_xx_save(uint8_t type)
{
  memset(&cf_storage_para, 0, sizeof(Cf_StorageParaType));
  
  cf_storage_para.para = Cf_RunPara;
  
  cf_storage_para.crc16 = crc16((uint8_t *)&cf_storage_para.para, sizeof(Cf_ParaType));
  
  eEPRom_Write(CF_STORAGE_ADDRESS, (const uint8_t*)&cf_storage_para, sizeof(Cf_StorageParaType));
  
  printf("Cf para save success.\r\n");
}

uint8_t Storage_xx_load(void)
{
  uint16_t crc;
  
  memset(&cf_storage_para, 0, sizeof(Cf_StorageParaType));
  
  eEPRom_Read(CF_STORAGE_ADDRESS, (uint8_t*)&cf_storage_para, sizeof(Cf_StorageParaType));
  
  crc = crc16((uint8_t *)&cf_storage_para.para, sizeof(Cf_ParaType));
  
  if(cf_storage_para.crc16 != crc)
  {
    printf("crc check error:0x%04X, 0x%04X\r\n", cf_storage_para.crc16, crc);
    storage_save_initpara();
    return 1;
  }
  
  if(Cf_ParaCheck(&cf_storage_para.para) != 0)
  {
    storage_save_initpara();
    return 2;
  }
  
  Cf_RunPara = cf_storage_para.para;
  
  return 0;
}
